import * as express from "express";
import * as bodyParser from "body-parser";

import { Request, Response } from "express";
import { AppDataSource } from "./data-source";
import { Routes } from "./routes";
import { Photo } from "./entity/Photo";
import { PhotoMetadata } from "./entity/PhotoMetadata.";
const cors = require("cors");

AppDataSource.initialize()
  .then(async (manager) => {
    // create express app
    const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    // register express routes from defined application routes
    Routes.forEach((route) => {
      (app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => {
        const result = new (route.controller as any)()[route.action](req, res, next);
        if (result instanceof Promise) {
          result.then((result) => (result !== null && result !== undefined ? res.send(result) : undefined));
        } else if (result !== null && result !== undefined) {
          res.json(result);
        }
      });
    });

    // setup express app here
    // ...
    // 创建 photo

    // 创建 photo metadata
    // let metadata = new PhotoMetadata();
    // metadata.height = 640;
    // metadata.width = 480;
    // metadata.compressed = true;
    // metadata.comment = "cybershoot";
    // metadata.orientation = "portait";

    // let photo = new Photo();
    // photo.name = "Me and Bears";
    // photo.description = "I am near polar bears";
    // photo.filename = "photo-with-bears.jpg";
    // photo.isPublished = true;
    // photo.views = 21.35;
    // photo.metadata = metadata;

    // // 获取实体 repositories

    // let metadataRepository = manager.getRepository(PhotoMetadata);
    // let photoRepository = manager.getRepository(Photo);

    // // 先保存photo
    // await metadataRepository.save(metadata);
    // await photoRepository.save(photo);

    // 然后保存photo的metadata

    // 完成
    console.log("Metadata is saved, and relation between metadata and photo is created in the database too");
    // start express server
    app.listen(3000);

    console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results");
  })
  .catch((error) => console.log(error));
